# coding: utf-8
from typing import Union

from qtpy.QtCore import Signal, Qt, QTimer, QPoint
from qtpy.QtGui import QPainter, QColor, QIcon
from qtpy.QtWidgets import QVBoxLayout, QHBoxLayout
from qfluentwidgets import FluentIcon as FIF, CaptionLabel, isDarkTheme, Action, RoundMenu, FluentIconBase
from qfluentwidgets.multimedia import MediaPlayer
from qfluentwidgets.multimedia.media_play_bar import MediaPlayBarButton, MediaPlayBarBase

from ..common import Icon
from .play_bar_button import FullScreenButton


class MediaPlayBar(MediaPlayBarBase):
    """
    播放栏小部件。
    """
    progressSliderMoved = Signal(int)
    rotated = Signal(bool)

    def __init__(self, parent=None):
        super().__init__(parent)
        # 初始化布局
        self.verticalLayout = QVBoxLayout(self)
        self.horizontalLayout = QHBoxLayout()
        self.toolsHorizontalLayout = QHBoxLayout()

        self.currentTimeLabel = CaptionLabel('0:00:00', self)
        self.remainTimeLabel = CaptionLabel('0:00:00', self)
        self.skipBackButton = MediaPlayBarButton(FIF.SKIP_BACK, self)
        self.skipForwardButton = MediaPlayBarButton(FIF.SKIP_FORWARD, self)
        self.rotationButton = MediaPlayBarButton(FIF.ROTATE, self)
        self.speedButton = MediaPlayBarButton(Icon.SPEED_1_0, self)
        self.fullScreenButton = FullScreenButton(self)
        self.timer = QTimer(self)

        self.setMediaPlayer(MediaPlayer(self))
        self.player: MediaPlayer

        self.__initWidgets()

    def __initWidgets(self):
        self.setFixedHeight(100)
        self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
        self.timer.setSingleShot(True)
        self.setMouseTracking(True)

        # 设置 tooltip
        self.skipBackButton.setToolTip(self.tr('快退'))
        self.skipForwardButton.setToolTip(self.tr('快进'))
        self.playButton.setToolTip(self.tr('播放'))
        self.rotationButton.setToolTip(self.tr('顺时针旋转45°'))
        self.speedButton.setToolTip(self.tr('播放速度'))
        self.fullScreenButton.setToolTip(self.tr('显示全屏'))
        # 设置布局
        self.__initLayout()
        # 设置信号
        self.__connectSignalToSlot()

    def __initLayout(self):
        """ initialize layout """
        self.horizontalLayout.addWidget(self.currentTimeLabel, 0,
                                        Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
        self.horizontalLayout.addWidget(self.progressSlider, 1, Qt.AlignmentFlag.AlignVCenter)
        self.horizontalLayout.addWidget(self.remainTimeLabel, 0,
                                        Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)

        self.toolsHorizontalLayout.addWidget(self.volumeButton)
        self.toolsHorizontalLayout.addStretch(1)
        self.toolsHorizontalLayout.addWidget(self.skipBackButton)
        self.toolsHorizontalLayout.addWidget(self.playButton)
        self.toolsHorizontalLayout.addWidget(self.skipForwardButton)
        self.toolsHorizontalLayout.addStretch(1)
        self.toolsHorizontalLayout.addWidget(self.rotationButton)
        self.toolsHorizontalLayout.addWidget(self.speedButton)
        self.toolsHorizontalLayout.addWidget(self.fullScreenButton)

        self.verticalLayout.addLayout(self.horizontalLayout)
        self.verticalLayout.addLayout(self.toolsHorizontalLayout)

    def __onMoreButtonClicked(self):
        menu = RoundMenu(parent=self)
        # 设置播放速度
        action0_5 = Action(Icon.SPEED_0_5, self.tr('1.5X'), self)
        action1_0 = Action(Icon.SPEED_1_0, self.tr('1.0X'), self)
        action1_25 = Action(Icon.SPEED_1_5, self.tr('1.25X'), self)
        action1_5 = Action(Icon.SPEED_1_5, self.tr('1.5X'), self)
        action1_75 = Action(Icon.SPEED_1_75, self.tr('1.75X'), self)
        action2 = Action(Icon.SPEED_2_0, self.tr('2.0X'), self)
        action0_5.triggered.connect(lambda: self.setPlaybackRate(0.5, Icon.SPEED_0_5))
        action1_0.triggered.connect(lambda: self.setPlaybackRate(1.0, Icon.SPEED_1_0))
        action1_25.triggered.connect(lambda: self.setPlaybackRate(1.25, Icon.SPEED_1_25))
        action1_5.triggered.connect(lambda: self.setPlaybackRate(1.5, Icon.SPEED_1_5))
        action1_75.triggered.connect(lambda: self.setPlaybackRate(1.75, Icon.SPEED_1_75))
        action2.triggered.connect(lambda: self.setPlaybackRate(2.0, Icon.SPEED_2_0))
        menu.addActions([action0_5, action1_0, action1_25, action1_5, action1_75, action2])
        menu.adjustPosition()

        x = (self.speedButton.width() - menu.width()) // 2 + 10
        pos = self.speedButton.mapToGlobal(QPoint(x, -menu.height() + self.speedButton.height() - 10))
        menu.exec(pos)

    def mouseMoveEvent(self, e):
        self.timer.stop()
        self.timer.start(3000)
        super().mouseMoveEvent(e)

    def showEvent(self, e):
        super().showEvent(e)
        self.timer.stop()
        self.timer.start(3000)

    def setPlaybackRate(self, rate: float, icon: Union[QIcon, str, FluentIconBase] = None):
        self.player.setPlaybackRate(rate)
        if icon:
            self.speedButton.setIcon(icon)

    def setCurrentTime(self, currentTime: int):
        """ 设置当前时间

        Parameters
        ----------
        currentTime: int
            current time in milliseconds
        """
        self.currentTimeLabel.setText(self.__parseTime(currentTime))
        self.progressSlider.setValue(currentTime)
        self.currentTimeLabel.adjustSize()

    @staticmethod
    def __parseTime(time: int) -> str:
        """ 将整型时间转换为字符串 """
        seconds = int(time / 1000)
        hours = seconds // 3600
        minutes = str(seconds // 60).rjust(2, "0")
        seconds = str(seconds % 60).rjust(2, "0")
        return f'{hours}:{minutes}:{seconds}'

    def __connectSignalToSlot(self):
        """ connect signal to slot """
        self.timer.timeout.connect(self.hide)

        # 不要使用 value change，否则声音会被打断
        self.skipBackButton.clicked.connect(lambda: self.skipBack(10000))
        self.skipForwardButton.clicked.connect(lambda: self.skipForward(30000))
        self.speedButton.clicked.connect(self.__onMoreButtonClicked)
        self.rotationButton.clicked.connect(self.rotated)

    def skipBack(self, ms: int):
        """ 快退指定毫秒数的媒体 """
        self.player.setPosition(self.player.position() - ms)

    def skipForward(self, ms: int):
        """ 快进指定毫秒数 """
        self.player.setPosition(self.player.position() + ms)

    def _onPositionChanged(self, position: int):
        super()._onPositionChanged(position)
        self.currentTimeLabel.setText(self._formatTime(position))
        self.remainTimeLabel.setText(self._formatTime(self.player.duration() - position))

    def _formatTime(self, time: int):
        time = int(time / 1000)
        s = time % 60
        m = int(time / 60)
        h = int(time / 3600)
        return f'{h}:{m:02}:{s:02}'

    def paintEvent(self, e):
        painter = QPainter(self)
        painter.setRenderHints(QPainter.RenderHint.SmoothPixmapTransform | QPainter.RenderHint.Antialiasing)

        if isDarkTheme():
            painter.setBrush(QColor(46, 46, 46, 100))
            painter.setPen(QColor(0, 0, 0, 20))
        else:
            painter.setBrush(QColor(248, 248, 248, 100))
            painter.setPen(QColor(0, 0, 0, 10))

        painter.drawRoundedRect(self.rect().adjusted(1, 1, -1, -1), 8, 8)
